const express = require('express');
const router = express.Router();
const redisClient = require('../server').redisClient;
const { POI } = require('../models/community');

// 获取附近环保点
router.get('/poi', async (req, res) => {
  try {
    const { lat, lng, radius } = req.query;
    const cacheKey = `poi:${lat},${lng},${radius}`;

    const cached = await redisClient.get(cacheKey);
    if (cached) {
      return res.json(JSON.parse(cached));
    }

    const pois = await POI.find({
      location: {
        $near: {
          $geometry: {
            type: 'Point',
            coordinates: [parseFloat(lng), parseFloat(lat)]
          },
          $maxDistance: parseInt(radius)
        }
      }
    });

    await redisClient.setEx(cacheKey, 1800, JSON.stringify(pois));
    res.json(pois);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: '获取环保点失败' });
  }
});

// 订阅活动通知
router.post('/subscribe', async (req, res) => {
  try {
    const { userId, activityTypes } = req.body;
    await redisClient.hSet(`user:${userId}:subscriptions`, 'activityTypes', activityTypes.join(','));
    res.json({ success: true });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: '订阅失败' });
  }
});

module.exports = router;